package com.blb.httptest;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Http接口测试案例
 */
public class HttpTestDemo {

    public void testGetStudentPage(){
        try {
            //创建URL对象
            URL url = new URL("http://localhost:8080/students-page?current=1&size=5");
            //获得http连接对象
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置连接超时
            connection.setConnectTimeout(2000);
            //设置请求方法
            connection.setRequestMethod("GET");
            //连接服务器
            connection.connect();
            //发送请求后获得响应码
            if(connection.getResponseCode() == 200){
                //读取响应的内容
                try(BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String line = null;
                    while((line = reader.readLine()) != null){
                        System.out.println(line);
                    }
                }catch (IOException ex){
                    ex.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void testAddStudent(){
        try {
            //创建URL对象
            URL url = new URL("http://localhost:8080/student");
            //获得http连接对象
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置连接超时
            connection.setConnectTimeout(2000);
            //设置请求方法
            connection.setRequestMethod("POST");
            //设置请求头，内容类型
            connection.addRequestProperty("Content-Type","application/json");
            //设置需要发送数据
            connection.setDoOutput(true);
            //连接服务器
            connection.connect();
            //发送学生json对象
            String student = "{\"stuId\":0,\"stuNo\":\"ST00999\",\"stuName\":\"大李\",\"stuAge\":22,\"stuAddress\":\"湖北武汉\",\"stuGender\":\"女\",\"stuTypeId\":1,\"stuPicture\":\"111.jpg\"}";
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(student.getBytes());
            outputStream.flush();
            //发送请求后获得响应码
            if(connection.getResponseCode() == 200){
                //读取响应的内容
                try(BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String line = null;
                    while((line = reader.readLine()) != null){
                        System.out.println(line);
                    }
                }catch (IOException ex){
                    ex.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        HttpTestDemo demo = new HttpTestDemo();
//        demo.testGetStudentPage();
        demo.testAddStudent();
    }
}
